package Servlst;

import db.Database;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(name = "RegisterServlet", value = "/Register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //统一编码格式
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");

        //创建输出
        PrintWriter out = response.getWriter();

        //验证密码是否正确
        if (password.equals(password2)) {
            try {
                Database database = new Database();
                //添加数据
                database.insert(username, password);
                out.println("<script type='text/javascript' >alert('注册成功');</script>");
                out.println("<script>window.location='index.jsp'</script>");
                out.println("请返回登录界面" + "<a href=\"http://localhost:8080/New_Login_war/\">返回登录</a>");
            } catch (ClassNotFoundException e) {
                out.println("注册失败1");
            } catch (SQLException e) {
                //账号存在会报错
                out.println("<script type='text/javascript' >alert('该账户已存在');</script>");
                out.println("<script>window.location='Register.jsp'</script>");
            }
        } else {
//            out.println("两次输入的密码不一致");
//            out.println("请返回重新注册" + "<a href=\"http://localhost:8080/New_Login_war/Register.jsp\">返回注册</a>");
            out.println("<script type='text/javascript' >alert('两次输入的密码不一致!');</script>");
            out.println("<script>window.location='Register.jsp'</script>");

        }
    }


}
